<?php

namespace ASW\Utility;


class Config
{
    const CONFIG_TYPE_ARRAY = 1;
    const CONFIG_TYPE_JSON  = 2;

    private static array $_config = [];

    /**
     * 加载配置项
     * @param string $filePath 配置文件路径
     * @param int $configType 配置文件类型
     */
    public static function load(string $filePath, int $configType = self::CONFIG_TYPE_ARRAY): void
    {
        $config = [];
        if (file_exists($filePath)) {
            if ($configType === self::CONFIG_TYPE_ARRAY) {
                $config = require($filePath);
            } elseif ($configType === self::CONFIG_TYPE_JSON) {
                $json   = file_get_contents($filePath);
                $config = json_decode($json, true);
            }

            self::$_config = array_replace_recursive(self::$_config, $config);
        }

        $localFilePath = dirname($filePath) . '/local/' . basename($filePath);
        if (file_exists($localFilePath)) self::load($localFilePath, $configType);
    }

    /**
     * 读取配置项
     * @param string $path
     * @param mixed|null $default
     * @return mixed
     */
    public static function get(string $path = "", mixed $default = null): mixed
    {
        if (empty($path)) return self::$_config;

        $keys = explode("/", $path);
        $val  = self::$_config;
        foreach ($keys as $key) {
            if (empty($key)) continue;
            if (empty($val)) return $default;
            if (!array_key_exists($key, $val)) return $default;
            $val = $val[$key];
        }

        return $val;
    }
}